package cn.jdy.plugins.service;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itextpdf.text.log.SysoCounter;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Label;


/**
 * @title 页签操作
 * @author Lutan
 * @since 1-12-2015
 */
@Service
public class LabelService extends BaseDao<Label>{

	@Autowired
	private ConfService confService;
	
	/**
	 * 按条件查询
	 * @param sp
	 * 
	 * @return
	 */
	public List<Label> query(Label sp){
		if(sp==null) return super.findAll();
		if(sp.getiDisplayLength() > 0){
	     return super.find(createFilter(sp),sp.getiDisplayStart(),sp.getiDisplayLength());
			}
		return super.find(createFilter(sp));
	}
	 public List<Label> querypage(Label sp){
	       return super.find(createFilter(sp),sp.getPageNo(),18);
	  }
	public Long count(Label sp){
		return super.count(createFilter(sp));
	}
	/**
	 * 拼装条件
	 * @param sp
	 * 
	 * @return
	 */
	private DetachedCriteria createFilter(Label sp){
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if(!StringUtil.isNullOrEmpty(sp.getName())) {
	        dc.add(Restrictions.like("name", sp.getName(),MatchMode.ANYWHERE));
		} 
		if(!StringUtil.isNullOrEmpty(sp.getUserid())) {
	        dc.add(Restrictions.eq("userid", sp.getUserid()));
		} 
		if(!StringUtil.isNullOrEmpty(sp.getLiveid())) {
	        dc.add(Restrictions.eq("liveid", sp.getLiveid()));
		} 
		if(!StringUtil.isNullOrEmpty(sp.getCreateTime())&&!",".equals(sp.getCreateTime())) {
   
        if( sp.getCreateTime().split(",").length>1){
          dc.add(Restrictions.between("createTime", sp.getCreateTime().split(",")[0], sp.getCreateTime().split(",")[1]));
        }else{
          dc.add(Restrictions.like("createTime", sp.getCreateTime(),MatchMode.ANYWHERE));
        }
     
    }
	
    	dc.addOrder(Order.asc("sort"));
		//dc.addOrder(Order.desc("createTime"));
			return dc;
	}
	/**
	 * 删除
	 * @param sp:一个Label对象

	@Transactional
    public void delLabel(Label sp){
		StringBuilder sql = new StringBuilder("delete ");
	    sql.append(entityClass.getSimpleName());
	    sql.append(" where ");
	        sql.append("and id").append("=").append(sp.getId());
	        hibernateTemplate.bulkUpdate(sql.toString(), null);
	}   */
  public List<Label> findbytype(int type, String addres, int i, int limitMax) {
    DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
    dc.add(Restrictions.eq("status", "1"));
        if(null != addres){
          dc.add(Restrictions.eq("address", addres));
        }
      if(type==0){// 根据类排序，0 表示目前根据创建时间排序 ， 以后可能会根据推广，销售量等等排序
        dc.addOrder(Order.desc("createTime"));
      }else{
        //以后会有字段或者方案
      }
      
      return super.find(dc,i,limitMax);
  }
  /**
	 *  删除
	 *
	 * @return String 删除用户信息的成功、失败信息
	 * @description: 删除指定用户标识的系统用户信息, 对多个系统用户信息的删除操作
	 * @param: id 用户标识（多个用户时用,号隔开）
	 * @author:lutan
	 * @date: 2017-03-23 16:40
	 */
	@Transactional
	public String delUserById(String userIds) {
		String backInfo = "0";
		try {
			String[] ids = userIds.split(",");
			// 删除用户
			super.delete(ids, "id");
			backInfo = "1";
		} catch(Exception e) {
			backInfo = "0"; // 删除失败
			BaseLog.e(this.getClass(), "删除页签", e);
			throw new BaseException("删除页签出错！", e);
		}
		return backInfo;
	}
	/**
	 * 根据兴趣班查询
	 * @param interestClassId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> querySiteMap(Long liveid) {
		String sql = "SELECT * FROM label WHERE liveid=:liveid ORDER BY sort";
		Query sqlQuery = super.em().createSQLQuery(sql);
		sqlQuery.setParameter("liveid", liveid);
		// 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
		sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return sqlQuery.list();
	}
	
	
	/**
	 * 根据兴趣班查询
	 * @param interestClassId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> queryLiveMap(Long liveid) {
		String sql = "SELECT labelid FROM label WHERE liveid=:liveid ORDER BY sort";
		Query sqlQuery = super.em().createSQLQuery(sql);
		sqlQuery.setParameter("liveid", liveid);
		// 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
		sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return sqlQuery.list();
	}
	
	public static String generate8RateUuid() {  
        String[] chars = new String[] { "a", "b", "c", "d", "e", "f",  
                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",  
                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",  
                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",  
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
                "W", "X", "Y", "Z" };  
        Random r = new Random();
        StringBuffer shortBuffer = new StringBuffer();  
        String uuid = UUID.randomUUID().toString().replace("-", "");  
        for (int i = 0; i < 8; i++) {  
            String str = uuid.substring(i * 4, i * 4 + 4);  
            int x = Integer.parseInt(str, 16);  
            shortBuffer.append(chars[x % 0x3E]);  
        }  
        return shortBuffer.toString()+(r.nextInt(899)+100);  
    }
	
    public void insertlabel(Long liveid,String userid){
		try {
			String aid="ff8080815bd13b41015bd"+generate8RateUuid();
			String bid="ff8080815bd13b41025bd"+generate8RateUuid();
			String cid="ff8080815bd13b41035bd"+generate8RateUuid();
			String did="ff8080815bd13b41045bd"+generate8RateUuid();
			String sql="INSERT INTO label (id,name,labelid,sort,liveid,userid) VALUES ('"+aid+"','详情','9888','1','"+liveid+"','"+userid+"'),"
					  +" ('"+bid+"','交流','9889','2','"+liveid+"','"+userid+"'),"
					  +"('"+cid+"','合作','9890','3','"+liveid+"','"+userid+"'),"
					  +"('"+did+"','关注','9891','4','"+liveid+"','"+userid+"');";
			SQLQuery sqlQuery = em().createSQLQuery(sql);
			sqlQuery.executeUpdate();
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "插入异常", e);
		}
		
	} 
    
}
